package com.ruoyi.verify.service.impl;

import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.ruoyi.verify.domain.VerifyLevel;
import com.ruoyi.verify.domain.VerifyTemplateContent;
import com.ruoyi.verify.mapper.VerifyLevelMapper;
import com.ruoyi.verify.mapper.VerifyTemplateContentMapper;
import com.ruoyi.verify.mapper.VerifyTemplateMapper;
import com.ruoyi.verify.utils.MyUtils;

import lombok.extern.slf4j.Slf4j;

import com.ruoyi.common.utils.StringUtils;

/**
 * 合同维护Service业务层处理
 *
 * @author ygx
 * @date 2020-08-04
 */

@Slf4j
@Service
public class GetContentServiceImpl  extends MyUtils {
	//大类
	static final String Class = "Class";
	//题目
	static final String Division = "Division";
	//选项
	static final String Section = "Section";
	//审核问卷id 类变量 并发写法（不按此写法，会造成变量并发时变量值混乱）
	private ThreadLocal<String> verifyid = new ThreadLocal<String>();
	//审核问卷父项id
	private ThreadLocal<String> parentid = new ThreadLocal<String>();
	//审核问卷选项id
	private ThreadLocal<String> childid = new ThreadLocal<String>();
	//排序 类变量 并发写法（不按此写法，会造成变量并发时变量值混乱）
	private ThreadLocal<Integer> ordernum = new ThreadLocal<Integer>();



    @Autowired
    private VerifyLevelMapper verifyLevelMapper;
    @Autowired
    private VerifyTemplateContentMapper verifyTemplateContentMapper;
    @Autowired
    VerifyTemplateMapper verifyTemplateMapper;


	/**
     * 解析审核模板详情
     * @param 审核模板详情
     * @return
     */
	@Transactional(rollbackFor = Exception.class)
    public String insertContent(String templateid,String type) {
    	String result ="1";
    	 ordernum.set(0);
    	String gettext = verifyTemplateMapper.selectVerifyTemplateById(templateid,"v").getContent();
    	if (gettext == null || StringUtils.isBlank(gettext))
    	{
    		result = "获取审核内容失败，请检查是否上传了审核内容，或联系管理员！";
    		return result;
    	}
    	if (!gettext.contains("供方等级划分说明") && !type.contains("VDA6.3"))
    	{
    		result = "模板中未找到等级划分，请确保模板中包含样式 '供方等级划分说明（总分≥85分为A级供方，70≤总分＜85分为B级供方，总分＜70分为C级供方，不合格。）'！ ";
    		log.warn(result);

    	    return result;
    	}
    	String[] texts = gettext.split("\n");
    	for (String text : texts)
    	{
    		//将正规则匹配需要用到的符号进行替换
    		text = text.replace("(", "（").replace(")", "）").replace("。", ".").replace("%", "％");
    		if (text.contains("供方等级划分说明"))
    		{
    			result = getlevel(text,templateid);
       			if (result != "1")
    			{
    				return result;
    			}
    		}
    		else {
    			if(type.contains("VDA6.3")){//不同审核类型可能会有不同的审核规则
					result = getVdaContent(text,templateid);
				}else{
					result = getContent(text,templateid);
				}
    			if (result != "1")
    			{
    				return result;
    			}
			}
    		}
    	return result;
    }

	/**
	 * 获取等级数据
	 * @param text
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
    public String getlevel(String text,String templateid){

    	String result = "1";
    	String[] levelinfos = text.split("，");
    	String scoretmp = "999";
    	String level = null;
    	for (String levelinfo : levelinfos){
    		 Pattern pl = Pattern.compile("[a-zA-Z]");
             Matcher ml = pl.matcher(levelinfo);
             while(ml.find()) {
           	   level = ml.group(0);
    	}
    		 Pattern ps = Pattern.compile("[1-9]?[0-9]{1}");
             Matcher ms = ps.matcher(levelinfo);
             String score = null;

             while(ms.find()) {
               if (score == null)
               {
            	    score = ms.group(0);
               }
             }
             if (score != null)
             {
            	 VerifyLevel verifyLevel = new VerifyLevel();
            	 verifyLevel.setTemplateid(templateid);
            	 verifyLevel.setLevelid(UUID.randomUUID().toString().replace("-", ""));
            	 verifyLevel.setLevel(level);
            	 verifyLevel.setCreateuser(getUserId());
            	 verifyLevel.setCreatedate(new Date());

             if (scoretmp != "999" &&  scoretmp.equals(score))
             {
            	 scoretmp = "-999";
            	 verifyLevel.setUpperscore(score);
            	 verifyLevel.setLowerscore(scoretmp);
            	 System.out.println("等级" + level + "最高分值" + score + "最低分" + scoretmp);
             }
             else
             {
            	 verifyLevel.setUpperscore(scoretmp);
            	 verifyLevel.setLowerscore(score);
             System.out.println("等级" + level + "最高分值" + scoretmp + "最低分" + score);
             }
             try {
				verifyLevelMapper.insertVerifyLevel(verifyLevel);
			} catch (Exception e) {
				result = "写入等级表失败，请联系管理员！";
				log.error(result, e);
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return result;
			}
			scoretmp = score;
         }
    	}

    	return result;
    }

    /**
     * 解析问卷并将数据插入问卷表
     * @param text
     * @return
     */

	@Transactional(rollbackFor = Exception.class)
    public String getContent(String text,String templateid)
    {
    	String result = "1";
    	String socre = "系统初始值";
    	String socreL = null;
    	String weight = "系统初始值";
    	String weightL = null;
    	VerifyTemplateContent verifyTemplateContent = new VerifyTemplateContent();

//          Pattern p = Pattern.compile("（[1-9]?[0-9]{1}分）");//正则表达式，取=和|之间的字符串，不包括=和|
          Pattern p = Pattern.compile("（-*[0-9]{1}[0-9]*分）");//正则表达式，取=和|之间的字符串，不包括=和|
          Matcher m = p.matcher(text);
          while(m.find()) {
        	   socre = m.group(0);
        	   socreL = socre.replaceAll("[^0-9]", "");

          }

              // 去除分数得到内容详情
        	  String newtext = text.replace(socre, "");
              String type = "初始类型";
    		  if (socreL == null && (newtext != null && StringUtils.isNotBlank(newtext)))
    		  {   socreL = socre.contains("-999") ?  "-999" : null;
    		     if (socreL == null)
    		     {
    			  result = newtext + "未取到分值，请检查模板，或联系管理员！";
    			  log.warn(result);
    			  return result;
    		     }
    		  }
    		// 将解析出的模板内容放入实体类
        	  if (newtext != null && StringUtils.isNotBlank(newtext))
        	  {
        		  verifyTemplateContent.setTemplateid(templateid);
        		  verifyTemplateContent.setCreatedate(new Date());
        		  verifyTemplateContent.setCreateuser(getUserId());
        		  int ordernumadd = this.ordernum.get();
        		  verifyTemplateContent.setOrdernum(ordernumadd++);
        		  this.ordernum.set(ordernumadd);
        		  if (checkClass(newtext))
        		  {
        		  verifyid.set(UUID.randomUUID().toString().replaceAll("-",""));
        		  type = Class;
        		  // 当类型为大类时，获取权重
        		  Pattern p1 = Pattern.compile("（[1-9]?[0-9]{1}％）");
    	          Matcher m1 = p1.matcher(text);
    	          while(m1.find()) {
    	        	  weight = m1.group(0);
    	        	  weightL = weight.replaceAll("[^0-9]+", "");
    	          }
	        	   if (StringUtils.isBlank(weightL) || weight.equals(weightL))
	        	   {
	        		   result = "未获取到 " + text + "的分值或权重比，请检查模板，或联系管理员！";
	        		   log.warn(result);
	        		   return result;
	        	   }
	        	   else {
	        		   weightL = weight.replaceAll("[^0-9]", "");
	        		   // 去除权重得到内容详情
	        		   newtext = newtext.replace(weight, "");
				}
    	          verifyTemplateContent.setWeight(weightL);
    	          verifyTemplateContent.setVerifyid(verifyid.get());
    	          verifyTemplateContent.setParentid("0");
        	      System.out.println(text);
        		  System.out.println("此数据为大类      " + newtext + "   分值为" + socreL + "  id为" + verifyid + ",父项id为0" + "序号为" + "权重为" + weightL);
        		  }
        		  if (checkDivision(newtext))
        		  {
            		  parentid.set(UUID.randomUUID().toString().replaceAll("-",""));
            		  type = Division;
        	          verifyTemplateContent.setVerifyid(parentid.get());
        	          verifyTemplateContent.setParentid(verifyid.get());
            	      System.out.println(text);
        		  System.out.println("此数据为题目      " + newtext + "   分值为" + socreL  + "  id为" + parentid + ",父项id为" + verifyid);

        		  }
        		  if (checkSection(newtext))
        		  {
            		  childid.set(UUID.randomUUID().toString().replaceAll("-",""));
            		  type = Section;
        	          verifyTemplateContent.setVerifyid(childid.get());
        	          verifyTemplateContent.setParentid(parentid.get());
            	      System.out.println(text);
        		  System.out.println("此数据为选项     " + newtext + "   分值为" + socreL  + "  id为" + childid + ",父项id为" + parentid);

        		  }
        		  //当一行数据不为大类、题目、选项时，认为此数据为换行数据，进行数据追加（此方法实现困难，直接注释）  采用抛出异常，用户自行修改 C:\Java-study\笔记本正式版本备份
        		  if ("初始类型".equals(type))
        		  {
        			  result = "内容" +newtext + "前存在换行，请删除换行后重新导入模板，或联系管理员！";
        			  log.warn(result);
        			  return result;
        		  }
            	  verifyTemplateContent.setContent(newtext);
            	  verifyTemplateContent.setType(type);
            	  verifyTemplateContent.setScore(socreL);
            	  try {
					verifyTemplateContentMapper.insertVerifyTemplateContent(verifyTemplateContent);
				} catch (Exception e) {
					result = "写入审核内容表失败，请联系管理员！";
					log.error(result, e);
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return result;
				}
        	  }

    	return result;
    }


	/**
	 * 解析问卷并将数据插入问卷表
	 * 根据问卷类型采用不同的解析规则
	 * @param text
	 * @return
	 */

	@Transactional(rollbackFor = Exception.class)
	public String getVdaContent(String text,String templateid)
	{
		String result = "1";
		String socre = "系统初始值";
		String socreL = null;
		String Asterisk = "0";
		String Asterisks = "";
		VerifyTemplateContent verifyTemplateContent = new VerifyTemplateContent();


		String type = "初始类型";

		// 将解析出的模板内容放入实体类
		if (StringUtils.isNotEmpty(text))
		{
			verifyTemplateContent.setTemplateid(templateid);
			verifyTemplateContent.setCreatedate(new Date());
			verifyTemplateContent.setCreateuser(getUserId());
			int ordernumadd = this.ordernum.get();
			verifyTemplateContent.setOrdernum(ordernumadd++);
			this.ordernum.set(ordernumadd);
			if (checkVdaClass(text))
			{
				verifyid.set(UUID.randomUUID().toString().replaceAll("-",""));
				type = Class;
				//VDA6.3审核每题分数均为10分，故不需要取分数
				verifyTemplateContent.setVerifyid(verifyid.get());
				verifyTemplateContent.setParentid("0");
			}
			if (checkVdaDivision(text))
			{
				// 当类型为题目时，获取是否为星号题目
				Pattern p1 = Pattern.compile("[0-9]\\*");
				Matcher m1 = p1.matcher(text);
				while(m1.find()) {
					Asterisks = m1.group(0);
					if(StringUtils.isNotEmpty(Asterisks)){
						Asterisk = "1";
					}
				}
				verifyTemplateContent.setAsterisk(Asterisk);
				parentid.set(UUID.randomUUID().toString().replaceAll("-",""));
				type = Division;
				verifyTemplateContent.setVerifyid(parentid.get());
				verifyTemplateContent.setParentid(verifyid.get());

			}
			if (checkSection(text))
			{
				childid.set(UUID.randomUUID().toString().replaceAll("-",""));
				type = Section;
				verifyTemplateContent.setVerifyid(childid.get());
				verifyTemplateContent.setParentid(parentid.get());

			}
			//VDA审核中认为不为大类、题目、选项的换行数据为题目的评分注意项
			if ("初始类型".equals(type))
			{
//				result = "内容" +text + "前存在换行，请删除换行后重新导入模板，或联系管理员！";
//				log.warn(result);
//				return result;
				childid.set(UUID.randomUUID().toString().replaceAll("-",""));
				type = Section;
				verifyTemplateContent.setVerifyid(childid.get());
				verifyTemplateContent.setParentid(parentid.get());
			}
			verifyTemplateContent.setContent(text);
			verifyTemplateContent.setType(type);

			try {
				verifyTemplateContentMapper.insertVerifyTemplateContent(verifyTemplateContent);
			} catch (Exception e) {
				result = "写入审核内容表失败，请联系管理员！";
				log.error(result, e);
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return result;
			}
		}

		return result;
	}

    /**
     * 判断输入的行是否为大类
     * @param newtext
     * @return
     */
    public boolean checkClass(String newtext)
    {
    	boolean result = false;
    	Pattern p = Pattern.compile("^[0-9]、[^0-9].*"); //^ 在[外代表以什么开头，在[内代表匹配除0-9之外的字符
    	Matcher m = p.matcher(newtext);
    	while(m.find())
    	{
    		if ( StringUtils.isNotBlank(m.group()) && m.group() != null)
    		{
    			result = true;
    		}
    	}
    	return result;
    }

	/**
	 * 判断输入的VDA6.3审核类型 行是否为大类
	 * @param newtext
	 * @return
	 */
	public boolean checkVdaClass(String newtext)
	{
		boolean result = false;
		Pattern p = Pattern.compile("(^[0-9]、)|(^[0-9]\\u002E[0-9]、)"); //此处匹配6、或者6.1、  也可写成^([0-99]\u002E([0-9])+[、])  *+的作用于为前一个[] ()
		Matcher m = p.matcher(newtext);
		while(m.find())
		{
			if ( StringUtils.isNotBlank(m.group()) && m.group() != null)
			{
				result = true;
			}
		}
		return result;
	}

	/**
	 * 判断VDA审核输入的行是否为题目
	 * @param newtext
	 * @return
	 */
	public boolean checkVdaDivision(String newtext)
	{
		boolean result = false;
		Pattern p = Pattern.compile("^([0-9]\\u002E[0-9][^、])"); // 仅匹配题目如 6.1 注意，当题目号为两位数时，此规则失效
		Matcher m = p.matcher(newtext);
		while(m.find())
		{
			if ( StringUtils.isNotBlank(m.group()) && m.group() != null)
			{
				result = true;
			}
		}
		return result;
	}

    /**
     * 判断输入的行是否为题目
     * @param newtext
     * @return
     */
    public boolean checkDivision(String newtext)
    {
    	boolean result = false;
    	Pattern p = Pattern.compile("^[0-99]\\u002E[0-99]*"); // \\u002E 代表 . 号
    	Matcher m = p.matcher(newtext);
    	while(m.find())
    	{
    		if ( StringUtils.isNotBlank(m.group()) && m.group() != null)
    		{
    			result = true;
    		}
    	}
    	return result;
    }

    /**
     * 判断输入的行是否为选项
     * @param newtext
     * @return
     */
    public boolean checkSection(String newtext)
    {
    	boolean result = false;
    	Pattern p = Pattern.compile("^[a-zA-Z].、*");
    	Matcher m = p.matcher(newtext);
    	while(m.find())
    	{
    		if ( StringUtils.isNotBlank(m.group()) && m.group() != null)
    		{
    			result = true;
    		}
    	}
    	return result;
    }


}
